package com.laxcen.intelligenttoy.BLE;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据转换工具类
 */
public class DataUtils {

    /**
     * 将int类型的数据转换为byte数组
     * 原理：将int数据中的四个byte取出，分别存储
     *
     * @param n int数据
     * @return 生成的byte数组
     */
    public static byte[] intToBytes2(int n) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (n >> (24 - i * 8));
        }
        return b;
    }

    /**
     * 一个byte为8个二进制位
     * 通常4个二进制转为一个十六进制
     * 一个byte可转为两个十六进制字符 如 f5
     *
     * @param b
     * @return
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xff);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    /**
     * byte数组转Hex字符串
     *
     * @param bytes
     * @return
     */
    public static String byteArrayToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = byteToHex(bytes[i]);
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 十六进制转byte
     * hex必须为十六进制字符串
     *
     * @param hex
     * @return
     */
    public static byte hexToByte(String hex) {
        return (byte) Integer.parseInt(hex, 16);
    }

    /**
     * 十六进制字符串转byte[]
     * hex必须为十六进制字符串
     *
     * @param hex
     * @return
     */
    public static byte[] hexToByteArray(String hex) {
        int hexlen = hex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            //奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            hex += "0";
        } else {
            //偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(hex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    /**
     * 字符串转换成十六进制字符串
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString();
    }

    /**
     * 16进制转换成为string类型字符串
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * byte数组转字符串，含空值
     *
     * @param src
     * @param dec
     * @param length
     * @return
     */
    public static String bytes2Str(byte[] src, int dec, int length) {
        byte[] temp = new byte[length];
        System.arraycopy(src, dec, temp, 0, length);
        return new String(temp);
    }

    /**
     * byte数组转字符串，不含空值
     *
     * @param src
     * @return
     */
    public static String bytes2Str(byte[] src) {
        return new String(src);
    }

    /**
     * 字符串转byte数组
     *
     * @param str
     * @return
     */
    public static byte[] str2Bytes(String str) {
        return str.getBytes();
    }

    /**
     * byte数组截取掉后面的空值
     *
     * @param src
     * @param dec
     * @param length
     * @return
     */
    public static byte[] cutBytes(byte[] src, int dec, int length) {
        byte[] temp = new byte[length];
        System.arraycopy(src, dec, temp, 0, length);
        return temp;
    }

    /**
     * 16进制转ASCII
     *
     * @param hex
     * @return
     */
    public static String hex2Str(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {
            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    /**
     * 合并BLE数据包
     *
     * @param byteArray  数据包列表
     * @param headLength 需要省略的数据包头
     * @return
     */
    public static byte[] mergeBytes(List<byte[]> byteArray, int headLength) {
        int mergeLength = 0;
        //计算合并后的数组长度
        for (byte[] bytes : byteArray) {
            mergeLength += (bytes.length - headLength);
        }
        byte[] mergeBytes = new byte[mergeLength];//创建合并后数组
        int pointer = 0;//当前指针
        for (byte[] bytes : byteArray) {
            int length = bytes.length - headLength;
            System.arraycopy(bytes, headLength, mergeBytes, pointer, length);//忽略数据包头
            pointer += length;
        }
        return mergeBytes;
    }

    /**
     * 拆分BLE数据包
     *
     * @param bytes 需要拆分的总包
     * @param head1 正常数据头
     * @param head2 尾包数据头
     * @return
     */
    public static List<byte[]> splitBytes(byte[] bytes, byte[] head1, byte[] head2) {
        List<byte[]> byteArrays = new ArrayList<>();
        byte[] bs1 = new byte[20];
//        byte[] bs2 = new byte[20];
//        byte[] bs3 = new byte[17];

        System.arraycopy(head1, 0, bs1, 0, 3);
        System.arraycopy(bytes, 0, bs1, 3, 17);

//        System.arraycopy(head1, 0, bs2, 0, 3);
//        System.arraycopy(bytes, 17, bs2, 3, 17);
//
//        System.arraycopy(head2, 0, bs3, 0, 3);
//        System.arraycopy(bytes, 34, bs3, 3, 14);

        byteArrays.add(bs1);
//        byteArrays.add(bs2);
//        byteArrays.add(bs3);
//        int pointer = 0;//当前指针
//        if(bytes.length <=17){
//            byte[] bs= new byte[20];
//            System.arraycopy(head1,0,bs,0,3);
//            System.arraycopy(bytes,0,bs,3,bytes.length);
//            byteArrays.add(bs);
//            return byteArrays;
//        }
//        for(int i=0;i<bytes.length;i+=17){
//            if(bytes.length - i < 17){
//                byte[] bs = new byte[];
//                System.arraycopy(head2,0,bs,0,3);
//                System.arraycopy(bytes,i,bs,3,bytes.length-i);
//            }else{
//                byte[] bs = new byte[20];
//                System.arraycopy(head1,0,bs,0,3);
//                System.arraycopy(bytes,i,bs,3,17);
//                byteArrays.add(bs);
//            }
//        }
        return byteArrays;
    }

    public static List<byte[]> splitBytes(byte[] bytes, byte[] head1) {
        List<byte[]> byteArrays = new ArrayList<>();
        byte[] bs1 = new byte[20];

        System.arraycopy(head1, 0, bs1, 0, 3);
        System.arraycopy(bytes, 0, bs1, 3, 17);

        byteArrays.add(bs1);
        return byteArrays;
    }

    public static List<byte[]> splitBytesNewBoard(byte[] bytes, byte[] head1) {
        List<byte[]> byteArrays = new ArrayList<>();
        byte[] bs1 = new byte[20];
        byte[] bs2 = new byte[20];

        System.arraycopy(head1, 0, bs1, 0, 1);

        System.arraycopy(head1, 0, bs2, 0, 1);
        System.arraycopy(bytes, 17, bs2, 1, 17);

        byteArrays.add(bs1);
        byteArrays.add(bs2);
        return byteArrays;
    }


    /**
     * 十六进制转正负数
     * <p>
     * (2个字节的)
     */
    public static double parseHex4(String num) {
        if (num.length() != 4) {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
        int ret = Integer.parseInt(num, 16);
        ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
        return (double) ret;
    }

    /**
     * 十六进制转负数
     * <p>
     * (4个字节的)
     *
     * @return
     */
    public static BigInteger parseHex8(String num) {
        if (num.length() != 8) {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
        BigInteger in = new BigInteger(num, 16);
        return in;
    }

}
